package com.brtbeacon.oauth2.verifytoken;

import com.brtbeacon.oauth2.verifytoken.utils.Constants;
import com.brtbeacon.oauth2.verifytoken.utils.EncryptUtil;
import com.brtbeacon.oauth2.verifytoken.utils.OcsSample;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

import javax.crypto.BadPaddingException;
import javax.crypto.IllegalBlockSizeException;
import java.io.UnsupportedEncodingException;

/**
 * Created by admin on 2017/7/13.
 */
public class CheckTokenUtil {
    private static final Logger log = LoggerFactory.getLogger(CheckTokenUtil.class);

    public static AccessToken verifyToken(String access_token,OcsSample ocsSample){
        AccessToken  accessToken = new AccessToken();
        accessToken.setStatus(Constants.TOKEN_INVALID);
        if (!StringUtils.isEmpty(access_token)&&!StringUtils.isEmpty(ocsSample)){
            EncryptUtil encryptUtil = EncryptUtil.getInstance();
            String decryToken = "";
            try {
                decryToken = new String(encryptUtil.decryptMode(encryptUtil.parseHexStr2Byte(access_token)),"UTF-8");
            } catch (Exception e) {
                log.info("token decryToken =========》》》{}","access_token 验证无效!");
                return accessToken;
            }
            try {
                JSONObject jsonToken = JSONObject.fromObject(decryToken);
                log.info("token decryToken =========》》》{}",decryToken);
                if (decryToken.equals(ocsSample.get(getTokenKey(jsonToken.getString("appkey"))))){   //判断 解密后的tonke与缓存是否一直
                    accessToken.setAppkey(jsonToken.getString("appkey"));
                    accessToken.setBuildingID(jsonToken.getString("buildingID"));
                    accessToken.setAppsecret(jsonToken.getString("appsecret"));
                    accessToken.setLevel(jsonToken.getString("level"));
                    accessToken.setStatus(Constants.TOKEN_CORRECT);
                }
            }catch (Exception e){
                return accessToken;
            }
        }
        return accessToken;
    }

    public static String getTokenKey (String appkey){
        String tokenKey = "oauth2-token-key-%s";
        return String.format(tokenKey,appkey);
    }


}
